package leetcode_day._2022._202201._2131;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/1/27 21:39
 * 句子中的有效单词数
 * 算法：模拟
 */
public class _27_2047 {

    public int countValidWords(String sentence) {
        String[] split = sentence.split(" ");
        int ans = 0;
        for (String s : split) if (check(s)) ++ans;
        return ans;
    }
    boolean check(String token) {
        int len = token.length();
        if (len == 0) return false;
        for (int i = 0, a = 0, b = 0; i < len; i++) {
            char c = token.charAt(i);
            if (c == ' ') return false;
            if (Character.isDigit(c)) return false;
            if (c == '-') {
                if (++a > 1 || (i == 0 || i == len - 1)) return false;
                if (!Character.isLetter(token.charAt(i - 1)) || !Character.isLetter(token.charAt(i + 1))) return false;
            }
            if (c == '!' || c == '.' || c == ',') {
                if (++b > 1) return false;
                if (i != len - 1) return false;
            }
        }
        return true;
    }

}
